package cn.springcloud.fix.samples.mq;

import cn.springcloud.fix.common.core.utils.json.JsonUtil;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;

public class MessageHelper {

    public static Message objToMsg(Object obj) {
        String msg = JsonUtil.objToStr(obj);
        if (msg == null) return null;

        Message message = MessageBuilder.withBody(msg.getBytes()).build();
        message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);// 消息持久化
        message.getMessageProperties().setContentType(MessageProperties.CONTENT_TYPE_JSON);
        return message;
    }

    public static <T> T msgToObj(Message message, Class<T> clazz) {
        if (null == message || null == clazz) {
            return null;
        }
        String str = new String(message.getBody());
        return JsonUtil.strToObj(str, clazz);
    }
}
